<?php

namespace App\Http\Controllers\Api\Admin;

use App\ChargeAvailable;
use App\ChargeRecord;
use App\Exceptions\OrderException;
use App\Express;
use App\Goods;
use App\OrderItem;
use App\OrderRefund;
use App\Orders;
use App\User;
use App\UserInfo;
use App\UserIntegralRecord;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class OrderController extends Controller
{
    public function changeOrderStatus(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereId($id)->first();
        if($thisOrder->status != 2)
            return response()->json(['level' => 'error','message' => '请保证订单为待发货状态']);

        if((!is_null($thisOrder->express_num) && $thisOrder->express_num != '') && (!is_null($thisOrder->express_time) && $thisOrder->express_time != '')){
            $thisOrder->status = 3;
            $thisOrder->save();
        }else{
            return response()->json(['level' => 'error','message' => '发货信息未完善']);
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisOrder]);
    }

    public function setShipInfo(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);

        $expressNum  = !is_null($request->get('express_num')) ? $request->get('express_num') : '';
        $expressId  = !is_null($request->get('express_id')) ? $request->get('express_id') : '';
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        if(!$expressNum)
            return response()->json(['level' => 'error','message' => '请填写单号']);
        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereId($id)->first();
        if(!$thisOrder || ($thisOrder && $thisOrder->status != 2))
            return response()->json(['level' => 'error','message' => '该订单不存在或状态不正确']);

        /** @var Express $thisExpress */
        $thisExpress = Express::whereId($expressId)->first();
        if(!$thisExpress)
            return response()->json(['level' => 'error','message' => '快递公司不存在']);

        if($expressNum != '')$thisOrder->express_num   = $expressNum;
        $thisOrder->express_time = date('Y-m-d H:i:s',time());
        $thisOrder->express      = $thisExpress->name;
        $thisOrder->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thisOrder]);
    }

    public function reSetOrderAmount(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $order_id   =$request->get('order_id');
        $amount     =$request->get('amount');

        if (!is_numeric($amount))
            return response()->json(['level'=>'error','message'=>'请输入金额']);

        $order=Orders::whereId($order_id)->first();
        if (!$order)
            return response()->json(['level'=>'error','message'=>'订单不存在']);

        if ($order->is_pay==1)
            return response()->json(['level'=>'error','message'=>'订单已支付，不能再修改了']);

        $order->s_amount=$amount ? round($amount,2) : 0;
        $order->save();
        return response()->json(['level'=>'success','message'=>'修改成功']);
    }
    public function setOrderRefund(Request $request){
        if(Auth::guard("admin")->guest())
            return response()->json(['level'=>'error','message' => '请先登录！']);
        $id   =$request->get('id');
        $status=$request->get('status');
        if (!in_array($status,['pass','deny','finish']))
            return response()->json(['level'=>'error','message'=>'参数错误']);
        $thisApply=OrderRefund::whereId($id)->first();
        if (!$thisApply)
            return response()->json(['level'=>'error','message'=>'该申请不存在']);
        if ($thisApply->status != 0)
            return response()->json(['level'=>'error','message'=>'该申请已处理']);
        $thisOrder=Orders::whereOrderNum($thisApply->order_num)->first();
        if (!$thisOrder)
            return response()->json(['level'=>'error','message'=>'订单不存在']);

        if ($status == 'pass'){
            $thisApply->status=1;
            if ($thisOrder->s_amount > 0){
                $this_user=User::whereId($thisOrder->user_id)->first();
                DB::beginTransaction();
                try {
                    //新增充值记录
                    $record = new ChargeRecord();
                    $record->user_id = $thisOrder->user_id;
                    if ($this_user->phone)
                        $record->phone = $this_user->phone;
                    $record->charge_money = round($thisOrder->s_amount, 2);
                    $record->remark = '订单退款';
                    $record->save();

                    //添加余额
                    $available = ChargeAvailable::whereUserId($this_user->id)->first();
                    if (!$available) {
                        $available = new ChargeAvailable();
                        $available->user_id = $this_user->id;
                        $available->amount = $record->charge_money;

                    } else {
                        $available->amount = $available->amount + $record->charge_money;
                    }
                    $available->save();
                } catch (\Exception $exception){
                    DB::rollback();
                    Log::error('chargeERROR=>'.$exception->getMessage());
                    return response()->json(['level'=>'error','message'=>'退款发生错误']);
                }
                DB::commit();
            }
        } elseif($status == 'deny')
            $thisApply->status=2;
        else
            $thisApply->status=3;
        $thisApply->save();
        $thisOrder->status=8;
        $thisOrder->save();

        return response()->json(['level'=>'success','message'=>'处理成功']);
    }
}
